import express from "express";
import expressSession from "express-session";
import { engine } from "express-handlebars";
import path, { format } from "path";
import { fileURLToPath } from "url";
import bodyParser from "body-parser";
import { credentials } from "./config.js"
// import { dbInit, closeDB } from "./models/db.js"
import { router } from "./router/router.js";
// 连接数据库
import { dbInit } from "./config/database.js";
import cors from 'cors'
const __dirname = path.dirname(fileURLToPath(import.meta.url));

const app = express();
const port = process.env.PORT || 3000;
app.use(cors())
// 使用内存存储的方式使用 Session
app.use(expressSession({ resave: false, saveUninitialized: false, secret: credentials.cookieSecret, 
  name: "myNotes", maxAge:60000 }));

app.use(bodyParser.urlencoded({ extended: true }));   // 使用 body-parser 表单解析中间件

app.use(express.static(__dirname + "/public"));   // 使用 public 文件夹置放静态网页
const getWeekTitle = {
  '1': '星期一',
  '2': '星期二',
  '3': '星期三',
  '4': '星期四',
  '5': '星期五',
  '6': '星期六',
  '7': '星期日'
}

const getWeatherTitle = {
  '1': '晴天',
  '2': '多云',
  '3': '阴天',
  '4': '雨天',
  '5': '雪天',
  '6': '雷暴',
  '7': '温暖',
  '8': '凉爽'
}
const eq = (a, b) => {
  return a == b
}
app.engine("hbs", engine({ drfalutLayout: "main", extname: ".hbs", helpers: {
  getWeekTitle: (week) => getWeekTitle[week],
  getWeatherTitle: (weather) => getWeatherTitle[weather],
  eq: eq
}  }));  // 产生 handlebars 模板引擎实例
app.set("view engine", ".hbs");   // 将模板引擎设定成 handlebars 引擎
app.set("views", "./views");    // 设定视图档目录
app.set("view cache", true);  // 使用视图缓存

dbInit();

app.use("/", router);

app.use((req, res) => {
  res.type("text/plain");
  res.status(404);
  res.send("404 - Not Found");
});

app.use((err, req, res, next) => {
  console.log(`${err.message}`);
  res.type("text/plain");
  res.status(500);
  res.send("500 - Server Error");
});

app.listen(port, () => {
  console.log(`Go visiting \u001b[34mhttp://localhost:${port}\u001b[0m , Press Ctrl-C to stop the server.`);
});